import React, { useState, useEffect, useRef, memo } from 'react';
import { Row, Col, Modal, message, Input, Form } from 'antd';
import styles from './index.less';
import classnames from 'classnames';
import EmptyCenter from '@/components/EmptyCenter';
import useModel from '../../useModels/useModel.js';
import { useUpdateEffect } from '@umijs/hooks';

export default memo(() => {
  const {
    state: { visible, suItemData, field, customMessageData },
    postCommand,
    setState,
    commandLoading,
  } = useModel(model => [
    model.state.visible,
    model.state.suItemData,
    model.state.field,
    model.commandLoading,
    model.state.customMessageData,
  ]);
  const [form] = Form.useForm();
  const formRef = useRef();

  const data = field;
  const keys = Object.keys(data);

  useUpdateEffect(() => {
    setTimeout(() => form.setFieldsValue({ ...field }), 0);
  }, [field]);

  const handleOk = async e => {
    const fields = form.getFieldsValue();
    const keys = Object.keys(fields);
    const hasError = keys.filter(item => {
      return !fields[item];
    });
    if (hasError[0]) {
      message.error(`${hasError.join(',')}字段不能为空！`);
      return;
    }
    await postCommand({
      id: customMessageData.id,
      suId: suItemData.suId,
      fsuTypeId: JSON.parse(localStorage.getItem('deviceType') || {}).id,
      data: fields,
    });

    setState({
      visible: false,
    });
  };

  const handleCancel = e => {
    setState({
      visible: false,
    });
  };

  return (
    <Modal
      closable={false}
      className={styles['modal-wrap']}
      title="报文相关KEY值填写"
      width={600}
      visible={visible}
      onOk={handleOk}
      okText={'确认'}
      onCancel={'取消'}
      destroyOnClose={true}
      confirmLoading={commandLoading}
      onCancel={handleCancel}
    >
      {visible && (
        <Form form={form} ref={formRef}>
          <Row className={styles['table-wrap']}>
            <Col span={24} className={styles['thead']}>
              <Row>
                <Col span={12}>KEY值名称</Col>
                <Col span={12}>VALUE值</Col>
              </Row>
            </Col>
            <Col span={24} className={styles['tbody']}>
              {!keys[0] && <EmptyCenter className={styles['border-bottom']} />}
              {keys[0] &&
                keys.map((item, index) => {
                  return (
                    <Row className={styles['tbody-tr']} key={index.toString(36) + index}>
                      <Col span={12}>{item}</Col>
                      <Col span={12} className={styles['input-wrap']}>
                        <Form.Item name={item}>
                          <Input placeholder="请输入内容" />
                        </Form.Item>
                      </Col>
                    </Row>
                  );
                })}
            </Col>
          </Row>
        </Form>
      )}
    </Modal>
  );
});
